package com.xiaoqian.partyembassy.base;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;
import com.xiaoqian.partyembassy.R;
import com.xiaoqian.partyembassy.constant.AppConfig;
import com.xiaoqian.partyembassy.tools.AppManagerUtil;
import com.xiaoqian.partyembassy.tools.OnPermissionListener;
import com.xiaoqian.partyembassy.tools.SharedPreUtils;
import com.xiaoqian.partyembassy.tools.ThreadPoolUtils;
import com.xiaoqian.partyembassy.view.DialogLoadingView;
import java.util.concurrent.TimeUnit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


/**
 * 项目名称:
 * 包: com.dnake.ifationhome.base
 * 类名称: BaseActivity
 * 类描述: activity基类
 * 创建人:黄飞
 * 修改人:
 * 修改时间:
 * 修改备注:
 * 版本: v1.0
 */
public abstract class BaseActivity extends AppCompatActivity {
    public String TAG = getClass().getSimpleName();
    private boolean isCreate = false;
    private AlertDialog dialog;
    private Toast mToast;
    // 上下文
    protected Context mContext;
    private WindowManager wManager;
    // 屏幕宽度
    protected int Width;
    // 屏幕高度
    private int Height;
    protected Bundle savedInstanceState;
    // 线程池管理类
    protected ThreadPoolUtils manager;
    // 状态栏高度
    // app接收心跳包服务
    // 设备请求数据弹出框
    protected DialogLoadingView mLoadingViewDialog;
    // 是否需要切换端口号
    // wifi是否连接标志
    //权限申请
    private OnPermissionListener onPermissionListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 添加到activity管理类
        // 注入布局
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(getLayoutId());
        AppManagerUtil.getAppManager().addActivity(this);
        this.savedInstanceState = savedInstanceState;
        // 初始化基础值
        initBaseData();
        // 获取屏幕状态栏高度
        SharedPreUtils.config(mContext);

    }

    /**
     * 规避因用户在设置中修改字体大小，导致布局错误
     *
     * @return
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 初始化基础属性
     */
    private void initBaseData() {
        // 初始化application
        mContext = this;

        // 页面是否创建标识
        mLoadingViewDialog = new DialogLoadingView(mContext);


        // 页面是否创建标识
        isCreate = true;
        // 创建线程池管理
        manager = ThreadPoolUtils.getInstance();
    }

    /**
     * isCreate ：true表示需要加载initParams()方法
     */

    @Override
    protected void onResume() {

        super.onResume();
        if (isCreate) {
            isCreate = false;
            initView();
            initParams();
        }

    }


    public void RefreshDialog() {
        if (null != mLoadingViewDialog) {
            mLoadingViewDialog.refreshTime();
        }
    }

    /**
     * 返回屏幕宽度
     *
     * @return Width 宽度
     */
    @SuppressWarnings("deprecation")
    public int getWidth() {

        wManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Width = wManager.getDefaultDisplay().getWidth();
        return Width;
    }

    /**
     * 返回屏幕高度
     *
     * @return Height 高度
     */
    @SuppressWarnings("deprecation")
    public int getHeight() {
        wManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Height = wManager.getDefaultDisplay().getHeight();
        return Height;
    }

    /**
     * 初始化布局
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化数据 Toast中使用getApplicationContext()来代替当前Activity的Context
     * 因为如果使用当前Activity的Context，当用户操作不当时，比如在Toast显示时候按了返回键，
     * 而此时Toast又持有当前Activity的Context引用，所以导致内存泄漏
     */
    protected abstract void initParams();

    /**
     * 初始化控件
     */
    protected abstract void initView();


    /**
     * app是否在前端运行
     *
     * @param isFroground
     */

    /**
     * 弹出toast信息
     *
     * @param text 内容
     */
    public void showToast(String text) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), text,
                    Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.setGravity(Gravity.CENTER, 0, 0);
        mToast.show();
    }

    /**
     * 弹出toast信息
     *
     * @param text 内容
     */
    public void showToast(int text) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), text,
                    Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.setGravity(Gravity.CENTER, 0, 0);
        mToast.show();
    }

    /**
     * 显示加载进度条 一般用于网络请求数据
     */
    public void ShowDialog() {
        if (dialog != null) {

            dialog.show();
        }
    }

    /**
     * 显示设备请求对话框
     */
    public void ShowLoaingViewDialog() {
        try {
            if (mLoadingViewDialog != null && !mLoadingViewDialog.isShowing()) {
                mLoadingViewDialog.show();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 显示设备请求对话框
     */
    public void dimissShowLoaingViewDialog() {
        try {
            if (mLoadingViewDialog != null && mLoadingViewDialog.isShowing()) {
                mLoadingViewDialog.dismiss();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }


    /**
     * 清空Toast
     */
    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

    /**
     * 取消进度条
     */
    public void disDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();

        }
    }

    /**
     * 取消设备数据进度条
     */
    public void disLoadingViewDialog() {
        if (mLoadingViewDialog != null && mLoadingViewDialog.isShowing()) {
            mLoadingViewDialog.dismiss();
        }
    }

    /**
     * 保存字符串
     *
     * @param id    键
     * @param value 值
     */
    protected boolean setStringShareValue(String id, String value) {
        return SharedPreUtils.setString(value, AppConfig.SAVEPATHNAME, id);
    }

    /**
     * 得到保存的字符串
     *
     * @param keyword 键
     * @return 值 （默认为""）
     */
    protected String getStringShareValue(String keyword) {
        return SharedPreUtils.getString(AppConfig.SAVEPATHNAME, keyword);
    }

    /**
     * 保存Int
     *
     * @param id    键
     * @param value 值
     */
    protected void setIntShareValue(String id, int value) {
        SharedPreUtils.setInt(value, AppConfig.SAVEPATHNAME, id);
    }

    /**
     * 获取Int
     *
     * @param keyword 键
     * @return 值（默认为0）
     */
    protected int getIntShareValue(String keyword) {
        return SharedPreUtils.getInt(AppConfig.SAVEPATHNAME, keyword);
    }

    /**
     * 保存Long
     *
     * @param id    键
     * @param value 值
     */
    protected void setLongShareValue(String id, long value) {
        SharedPreUtils.setLong(value, AppConfig.SAVEPATHNAME, id);
    }


    /**
     * 保存Boolean
     *
     * @param id    键
     * @param value 值
     */
    protected void setBooleanShareValue(String id, Boolean value) {
        SharedPreUtils.setBoolean(value, AppConfig.SAVEPATHNAME, id);
    }

    /**
     * 获取Boolean
     *
     * @param keyword 键
     * @return 值 （默认true）
     */
    protected boolean getBooleanShareValue(String keyword) {
        return SharedPreUtils.getBoolean(true, AppConfig.SAVEPATHNAME, keyword);

    }

    /**
     * 清除所有sharePre数据
     */
    protected void cleanAllData() {
        SharedPreUtils.clearAllData(AppConfig.SAVEPATHNAME);
    }

    /**
     * 不含参数的Class跳转
     **/
    protected void startActivity(Class<?> cla) {
        Intent intent = new Intent();
        intent.setClass(this, cla);
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 不含参数的Class跳转
     **/
    protected void startActivitys(Class<?> cla) {
        Intent intent = new Intent();
        intent.setClass(this, cla);
        startActivity(intent);
        defaultFinish();

        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 不含参数的Class跳转,有请求码
     **/
    protected void startActivityWithCode(Class<?> cla, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cla);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有bundle，有请求码
     **/
    protected void startActivityWithCodeAndBundle(Class<?> cls, Bundle bundle,
                                                  int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 不含参数的Class跳转,关闭本界面
     **/
    protected void startActivityAndFinish(Class<?> cla) {
        Intent intent = new Intent();
        intent.setClass(this, cla);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有Bundle通过Class跳转界面,有请求码
     **/
    protected void startActivityWithCode(Class<?> cls, Bundle bundle,
                                         int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        //overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有Bundle通过Class跳转界面,关闭界面
     **/
    protected void startActivityAndFinish(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有String通过Class跳转界面,有请求码
     **/
    protected void startActivityWithCode(Class<?> cls, String key,
                                         String value, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtra(key, value);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有String通过Class跳转界面,有请求码
     **/
    protected void startActivityWithCode(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有String通过Class跳转界面,有请求码
     **/
    protected void startActivityWithIntent(Intent intent) {
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    protected void startActivityWithIntent(Class<?> cls, Intent intent) {
        if (intent != null) {
            intent.setClass(mContext, cls);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in,
                R.anim.push_left_out);

    }

    /**
     * 含有String通过Class跳转界面,有请求码
     **/
    protected void startActivityWithIntentAndFinish(Intent intent) {
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 含有String通过Class跳转界面,
     **/
    protected void startActivity(Class<?> cls, String key, String value) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtra(key, value);
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 带有右进左出的动画退出
     **/
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.back_left_in, R.anim.back_right_out);

    }

    /**
     * 默认退出
     **/
    public void defaultFinish() {
        super.finish();
    }

    @Override
    protected synchronized void onDestroy() {
        super.onDestroy();
        // 销毁所有的activity
        AppManagerUtil.getAppManager().finishActivity(this);
        // 取消所有的进度框
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }

        if (mLoadingViewDialog != null && mLoadingViewDialog.isShowing()) {
            mLoadingViewDialog.dismiss();
            mLoadingViewDialog = null;
        }


    }

    /**
     * 权限申请
     *
     * @param permission
     * @param onBooleanListener
     */

    public void onPermissionRequests(String permission, OnPermissionListener onBooleanListener) {
        onPermissionListener = onBooleanListener;
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_CONTACTS)) {
                //权限已有
                onPermissionListener.onPermissionRequest(true);
            } else {
                //没有权限，申请一下
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        1);
            }
        } else {
            onPermissionListener.onPermissionRequest(true);
            Log.d("MainActivity", "2" + ContextCompat.checkSelfPermission(this,
                    permission));
        }
    }

    /**
     * 通过尝试打开相机的方式判断有无拍照权限（在6.0以下使用拥有root权限的管理软件可以管理权限）
     *
     * @return
     */
    public static boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            if (null != grantResults) {
                int length = grantResults.length;
                if (length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //权限通过
                        if (onPermissionListener != null) {
                            onPermissionListener.onPermissionRequest(true);
                        }
                    } else {
                        //权限拒绝
                        if (onPermissionListener != null) {
                            onPermissionListener.onPermissionRequest(false);
                        }
                    }
                }
                return;
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }






    @Override
    protected void onPause() {

        super.onPause();
        disLoadingViewDialog();
        cancel();
    }

    private Disposable mDisposable;

    protected void countDown(int time) {
        cancel();
        Observable.timer(time, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //取消订阅
                        cancel();
                    }

                    @Override
                    public void onComplete() {
                        //取消订阅
                        dissmissShow();
                        cancel();
                    }
                });
    }

    /**
     * 取消订阅
     */
    public void cancel() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    protected void dissmissShow() {
    }



}
